<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>数组统计</title>
  </head>
  <body>
    <script>
      // [6, 5, 5, 5, 7, 8, 7, 9]
      // [{val: 5, num: 3}, {val: 7, num: 2}]
      let data = [6, 5, 5, 5, 7, 8, 7, 9]
      // let data = {a: 1, b: 2, length: 3}
      function createItem(val) {
        return {
          val: val,
          num: 1
        }
      }
      function getStat(data, limit = 2) {
        let result = []
        if (Object.prototype.toString.call(data) !== '[object Array]') return 'data not array'
        data.forEach(val => {
          let r = result.find(item => {
            return item.val === val
          })
          if (r) {
            r.num++
          } else {
            // result.push(createItem(val))
            result.push({val, num: 1})
          }
        })
        result = result.filter(item => {
          return item.num >= limit
        })

        return result
      }
      console.log(getStat(data, 2))

      function getStat2(data, limit = 2) {
        let result = []
        data.sort()
        let len = data.length
        for (let i = 0; i < len; ) {
          let count = 0
          for (let j = i; j < len; j++) {
            if (data[i] === data[j]) {
              count += 1
            }
          }
          if (count >= limit) {
            result.push({
              val: data[i],
              num: count
            })
          }
          i += count
        }

        return result
      }
      console.log(getStat2(data, 2))
    </script>
  </body>
</html>
